package com.junqson.je.common.exception;

import com.junqson.je.common.model.ApiResult;
import com.junqson.je.common.model.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @Descriptions 统一异常处理
 * @Company
 * @Author Junqson
 * @Date 2020/1/20 23:43
 * @Version 1.0
 */
@ControllerAdvice
@Slf4j
public class ExceptionHandle {


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ApiResult handle(Exception e) {
        if (e instanceof BizException) {
            BizException myException = (BizException) e;
            log.error("[业务异常]: code: {}, msg: {}", myException.getCode(), myException.getMessage());
            return ApiResult.error(myException.getCode(), myException.getMessage());
        } else {
            log.error("[系统异常]", e);
            // 方便查找堆栈
//            StringWriter sw = new StringWriter();
//            e.printStackTrace(new PrintWriter(sw));
            e.printStackTrace();
            return ApiResult.error(ResultEnum.SYSTEM_ERROR);

        }
    }
}
